package org.academic.texteditor.gui.plugin.reference;

import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.List;

import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;

import org.academic.texteditor.gui.component.PageContainer;
import org.academic.texteditor.gui.component.PersonalizedTextPane;
import org.academic.texteditor.gui.component.menu.MenuFactory;
import org.academic.texteditor.gui.feature.Page;
import org.academic.texteditor.gui.helper.Reference;
import org.academic.texteditor.gui.plugin.BasePlugin;

public class AuthorShortcutPlugin extends BasePlugin {

	private static final long serialVersionUID = -8777358273412141009L;

	private PageContainer pageContainer;

	public AuthorShortcutPlugin() {
		super("authorShortcutPlugin");
	}

	@Override
	public void initialize(PageContainer pageContainer) {
		this.pageContainer = pageContainer;
	}
	
	@Override
	public void activate() {
		JMenu menu = MenuFactory.getReference();
		MenuFactory.createMenuItem(menu, -1, "authors", "menu.reference.authors", this).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK));
		
		menu.setVisible(true);
	}

	
	@Override
	public void execute() {
		Page page = pageContainer.getActualPage();
		PersonalizedTextPane textPane = page.getText().getTextPane();
		
		JPopupMenu popup = new JPopupMenu();
		popup.addSeparator();
		List<Reference> references = pageContainer.getReferences();
		for (Reference reference : references) {
			popup.add(createMenuItem(reference.toString(), textPane));
		}

		popup.setInvoker(textPane);

		Rectangle view;
		try {
			view = textPane.modelToView(textPane.getCaretPosition());
		} catch (BadLocationException e) {
			throw new RuntimeException("", e);
		}
		popup.show(textPane, view.x, view.y + view.height);
	}

	private JMenuItem createMenuItem(String title, final PersonalizedTextPane textPane) {
		JMenuItem menuItem = new JMenuItem(title);
		menuItem.setActionCommand(title);
		menuItem.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					textPane.getDocument().insertString(textPane.getCaretPosition(), e.getActionCommand(), null);
				} catch (BadLocationException e1) {
					
				}
			}
		});
		
		return menuItem;
	}

	@Override
	public void deactivate() {
		JMenu menu = MenuFactory.getReference();
		MenuFactory.removeMenuItem(menu, "authors");
		menu.setVisible(false);
	}

	@Override
	public void destroy() {

	}
	
}
